#include "BoardCairoViewer.h"
#include "board.h"
#include <math.h>
#include <cairomm/context.h>
#include <gtkmm.h>

BoardCairoViewer::BoardCairoViewer(Board& board)
  : Gtk::Table(Board::ROWS + 2, Board::COLS + 2),board_(board)
{

    for(int i = 0; i < Board::ROWS + 2; ++i){
        for(int j = 0; j < Board::COLS + 2; ++j){
            matrix_[i][j].set_color(board_(i, j));
            attach(matrix_[i][j], i, i + 1, j, j + 1);
        }
    }
    show_all_children();
}
void BoardCairoViewer::draw()
{
}
void BoardCairoViewer::update(int row, int col, Color color)
{
    matrix_[row][col].set_color(color);
    matrix_[row][col].on_expose_event(NULL);
    
    
}

BoardCairoViewer::~BoardCairoViewer(){
}
//for internal class Chess
void BoardCairoViewer::Chess::draw_circle(CR cr)
{
    int width, height ;
    get_size_request(width, height);
    int ra = (width*2) / 5;
    cr->arc (width / 2, height / 2, ra, 0, 2 * M_PI);
    if(color_ == White){
        cr->set_source_rgb(250, 0, 0);
    }else if(color_ == Black){
        cr->set_source_rgb(0, 0, 0);
    }
    cr->fill();
}
void BoardCairoViewer::Chess::set_color(Color color)
{
    color_ = color;
}

BoardCairoViewer::Chess::Chess()
{
    //add_events(Gdk::BUTTON_PRESS_MASK);    
    set_size_request (60, 60);
}
bool
BoardCairoViewer::Chess::on_expose_event(GdkEventExpose* event)
{
    Glib::RefPtr<Gdk::Window> window = get_window();
    CR cr = window->create_cairo_context();
    if(color_ == Empty){
        draw_rectangle(cr);
        return true;
    }
    if(color_== Black || color_ == White){
        draw_rectangle(cr);        
        draw_circle(cr);
        return true;
    }

    if(color_ == Fense){
        return true;
    }
    return false;
}
void
BoardCairoViewer::Chess::draw_rectangle(CR cr)
{
    int width, height;
    get_size_request(width, height);
    cr->rectangle (0, 0, width, height);
    cr->set_source_rgb(0, 0, 0);
    cr->stroke();
}

